<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="primary"
                   size="small"
                   :disabled="warehouseId===undefined"
                   icon="el-icon-plus"
                   @click="spuShow=true">新增库存信息
        </el-button>
        <el-tooltip class="item" effect="dark" content="当您选择仓库并点击搜索后此按钮才可用" placement="top-start" style="margin-right: 20px">
          <i class="el-icon-question"></i>
        </el-tooltip>


        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.stock_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
    </avue-crud>

    <el-dialog title="所有可选择商品"
               style="margin-top: -10vh;"
               :visible.sync="spuShow"
               width="80%">
      <avue-crud :option="spuOption"
                 :table-loading="spuLoading"
                 :data="spuData"
                 :page="spuPage"
                 ref="crud"
                 @search-change="spuSearchChange"
                 @search-reset="spuSearchReset"
                 @current-change="spuCurrentChange"
                 @size-change="spuSizeChange"
                 @on-load="spuOnLoad">
        <template slot-scope="scope" slot="menu">
          <el-button type="text"
                     icon="el-icon-menu"
                     size="small"
                     plain
                     style="border: 0;background-color: transparent !important;"
                     @click="handleShowSku(scope.row)">选择规格
          </el-button>
        </template>
      </avue-crud>

    </el-dialog>
    <el-dialog title="入库规格选择"
               :visible.sync="skuBox"
               width="60%">
      <avue-crud :data="skuData"
                 :option="skuOption"
                 @on-load="skuLoad"
                 :table-loading="skuLoading"
                 ref="skuCrud"
                 @search-change="skuSearchChange"
                 @search-reset="skuSearchReset"
                 @current-change="skuCurrentChange"
                 :page="skuPage"
                 @size-change="skuSizeChange">
        <template slot-scope="scope" slot="menu">
          <el-button type="text"
                     icon="el-icon-plus"
                     size="small"
                     plain
                     style="border: 0;background-color: transparent !important;"
                     @click="handleAddStock(scope.row)">加入库存
          </el-button>
        </template>
      </avue-crud>
    </el-dialog>

  </basic-container>
</template>

<script>
  import {getPage, getDetail, add, update, remove} from "@/api/warehouse/stock";
  import {getSpuPage} from "@/api/product/spu";
  import {getSkuPage, getSkuDetail, addSku, updateSku, removeSku} from "@/api/product/sku";
  import {mapGetters} from "vuex";
  import {getWareList} from "@/api/warehouse/logistics";
  export default {
    data() {
      return {
        selectSpu:0,
        /*以下为sku列表所需curd数据*/
        skuId:0,
        skuBox:false,
        skuLoading:true,
        skuQuery:{},
        skuSelectionList: [],
        skuData:[],
        skuPage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        skuOption:{
          menu:true,
          menuWidth: 150,
          viewBtn: false,
          editBtn: false,
          addBtn: false,
          delBtn: false,
          searchShow: true,
          tip: false,
          tree: true,
          border: true,
          index: true,
          selection: true,
          column: [
            {
              label: "标题",
              prop: "skuTitle",
              searchSpan:8,
              search: true,
              rules: [{
                required: false,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "价格",
              searchSpan:8,
              prop: "skuPrice",
              search: true,
              rules: [{
                required: false,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "规格",
              searchSpan:8,
              prop: "saleAttr",
              editDisplay:false,
              search: true,
              rules: [{
                required: false,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "图片",
              prop: "skuImage",
              type: "upload",
              listType: 'picture-img',
            }
          ]
        },
        //以下为spu数据
        spuShow:false,
        spuId:0,
        spuQuery: {},
        spuLoading: true,
        spuPage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        spuData:[],
        spuOption: {    excelBtn:true,
          menu:true,
          menuWidth: 200,
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          tip: false,
          border: true,
          index: true,
          viewBtn: false,
          delBtn:false,
          editBtn:false,
          selection: false,
          addBtn:false,
          column: [
            {
              label: "ID",
              prop: "id",
              hide:true,
              editDisplay: false,
              search: true,
              rules: [{
                required: false,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "标题",
              prop: "spuTitle",
              search: true,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "副标题",
              prop: "spuInfo",
              rules: [{
                required: true,
                message: "请输入副标题",
                trigger: "blur"
              }]
            },

            {
              label: "所属分类",
              prop: "spuCategory",
              search:true,
              type: "tree",
              dicUrl: "/api/ocm-product/category/list",
              props: {
                label: "categoryName",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请输入所属分类",
                trigger: "click"
              }]
            },
            {
              label: "邮费",
              prop: "spuPostage",
              rules: [{
                required: true,
                message: "请输入邮费",
                trigger: "blur"
              }]
            },
            {
              label: "视频",
              prop: "spuVideo",
              accept:"video/mp4",
              type: "upload",
              listType: 'picture-img',
            },
            {
              label: "主图",
              prop: "spuThumb",
              type: "upload",
              listType: 'picture-img',
              propsHttp: {
                res: 'data',
                url: 'link',
              },
            },
            {
              label: "图片",
              hide:true,
              dataType: 'string',
              type: "upload",
              row:true,
              span:24,
              listType: 'picture-card',
              prop: "spuImages",
              rules: [{
                required: true,
                message: "请输入图片",
                trigger: "blur"
              }]
            },
            {
              label: "图片详情",
              hide:true,
              prop: "spuDescribe",
              dataType: 'string',
              type: "upload",
              row:true,
              span:24,
              listType: 'picture-card',
            },
            {
              label: "当前状态",
              search:true,
              prop: "status",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dicUrl: "/api/ocm-system/dict/dictionary?code=product_status",
              type: 'select',
              rules: [{
                required: true,
                message: "请输入0已下架 1待上架 2审核中 3已上架",
                trigger: "blur"
              }]
            },
            {
              label: "商品类型",
              search:true,
              prop: "spuType",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dicUrl: "/api/ocm-system/dict/dictionary?code=product_type",
              type: 'select',
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
          ]
        },
        //库存
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {    excelBtn:true,
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          column: [
            {
              hide:true,
              editDisplay:false,
              label: "ID",
              prop: "id",
              rules: [{
                required: true,
                message: "请输入主键",
                trigger: "blur"
              }]
            },
            {
              editDisplay:false,
              label: "仓库名",
              prop: "warehouseName",
              rules: [{
                required: true,
                message: "请输入主键",
                trigger: "blur"
              }]
            },
            {
              label: "商品名",
              prop: "spuTitle",
              search: true,
              editDisplay:false,
              rules: [{
                required: true,
                message: "请输入商品id",
                trigger: "blur"
              }]
            },
            {
              label: "图片",
              editDisplay:false,
              prop: "spuThumb",
              type:'img',
              rules: [{
                required: true,
                message: "请输入商品id",
                trigger: "blur"
              }]
            },
            {
              label: "规格",
              editDisplay:false,
              prop: "saleAttr",
              search: true,
              rules: [{
                required: true,
                message: "请输入规格id",
                trigger: "blur"
              }]
            },
            {
              label: "库存数量",
              prop: "stockNumber",
              rules: [{
                required: true,
                message: "请输入库存数量",
                trigger: "blur"
              }]
            },
            {
              label: "待发数量",
              prop: "stockLock",
              editDisplay: false,
              rules: [{
                required: true,
                message: "请输入库存数量",
                trigger: "blur"
              }]
            },
            {
              label: "所属仓库",
              editDisplay:false,
              hide: true,
              search:true,
              viewDisplay:false,
              prop: "warehouseId",
              viewDispaly:false,
              children: {
                border: true,
                index: true,
                viewBtn: true,
                column: [
                  {
                    label: '仓库名',
                    width: 120,
                    search:true,
                    searchSpan:8,
                    prop: 'warehouseName'
                  }, {
                    label: "类型",
                    prop: "warehouseType",
                    type: "select",
                    props: {
                      label: "dictValue",
                      value: "dictKey"
                    },
                    search:true,
                    dicUrl: "/api/ocm-system/dict/dictionary?code=warehouse_type",
                    rules: [{
                      required: true,
                      message: "请输入0 官方仓库 1个人仓库 2合作仓库",
                      trigger: "blur"
                    }]
                  }, {
                    label: '所有者',
                    prop: 'warehouseOwner'
                  }],
              },

              onLoad: ({ page, value,data }, callback) => {
                //bug影响 仅能加此代码消除
                if (value) {
                  return
                }
                //bug结束
                let wareData=[];
                if("undefined" ==typeof page){
                  page={
                    currentPage:1,
                    pageSize:10
                  }
                }
                getWareList(page.currentPage, page.pageSize,data).then(res => {
                  wareData = res.data.data;
                  callback({
                    total: wareData.total,
                    data:  wareData.records
                  })
                });
              },
              props: {
                label: "warehouseName",
                value: "id"
              },
              type:'table',
              placeholder:'请选择仓库',
              rules: [{
                required: true,
                message: "请选择仓库",
                trigger: "blur"
              }]
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: false,
          viewBtn: this.vaildData(this.permission.stock_view, false),
          delBtn: this.vaildData(this.permission.stock_delete, false),
          editBtn: this.vaildData(this.permission.stock_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      handleAddStock(row){
        console.log(row)
        this.$prompt('请输入入库数量', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {
          let data={
            spuId:row.spuId,
            skuId:row.id,
            warehouseId:this.warehouseId,
            stockNumber:value
          }
          add(data).then(() => {
            this.skuBox=false
            this.attrBox=false
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          }, error => {
            window.console.log(error);
            loading();
          });

        })

      },
      handleShowSku(spu){
        this.selectSpu=spu
        this.spuId=spu.id
        this.skuLoad()
        this.skuBox = true
      },
      //sku
      skuLoad(){
        getSkuPage(this.skuPage.currentPage, this.skuPage.pageSize,
          Object.assign(this.skuQuery,
            {'k.spuId_equal':this.spuId})
        ).then(res => {
          this.skuLoading=true;
          const data = res.data.data;
          this.skuData = data.records;
          this.skuLoading = false;
          this.skuPage.total = data.total;
        });
      },
      skuSearchChange(params, done) {
        this.skuQuery = params;
        this.skuLoad();
        done();
      },
      skuSearchReset() {
        this.skuQuery = {};
        this.skuLoad();
      },
      skuCurrentChange(currentPage){
        this.skuPage.currentPage = currentPage;
      },
      skuSizeChange(pageSize){
        this.skuPage.pageSize = pageSize;
      },
      //spu方法
      spuOnLoad(page, params = {}) {
        this.spuLoading = true;
        getSpuPage(page.currentPage, page.pageSize, Object.assign(params, this.spuQuery)).then(res => {
          const data = res.data.data;
          this.spuPage.total = data.total;
          this.spuData = data.records;
          this.spuLoading = false;
        });
      },
      spuSearchReset() {
        this.spuQuery = {};
        this.spuOnLoad(this.spuPage);
      },
      spuSearchChange(params, done) {
        this.spuQuery = params;
        this.spuPage.currentPage = 1;
        if(this.spuQuery.shopName!==null){
          this.spuQuery['s.shopName']=this.query.shopName
          this.spuQuery.shopName=null
        }
        this.spuOnLoad(this.spuPage,params);
        done();
      },
      spuCurrentChange(currentPage){
        this.spuPage.currentPage = currentPage;
      },
      spuSizeChange(pageSize){
        this.spuPage.pageSize = pageSize;
      },
      //
      rowSave(row, done, loading) {
        add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {

          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getPage(page.currentPage, page.pageSize, Object.assign(params,{warehouseId_notequal: 0}, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.warehouseId= this.query.warehouseId
          console.log(this.warehouseId)
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
